<?php

namespace App\Http\Controllers\wx;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repos\OrderRepo;
use App\Repos\AdminRepo;
use App\Repos\OrderGroupRepo;
use App\Repos\ProductRepo;

use App\Services\WechatTpl;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderGroup;
use App\Models\OrderProduct;
use App\Models\Product;
use App\Models\ShopUser;
use Carbon\Carbon;
use EasyWeChat,Log;
use EasyWeChat\Factory;

class PayController extends Controller
{
    public function payNotify()
    {
    	$config = config('wechat.payment.default');    	
    	$app = Factory::payment($config);
    	Log::info('进入回调：');
    	$response = $app->handlePaidNotify(function($message, $fail){
		    // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单

		    $order = OrderRepo::find(['code'=>$message['out_trade_no']]);

		    if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
		        return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
		    }

		   

	if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
		        // 用户是否支付成功
		        if (array_get($message, 'result_code') === 'SUCCESS') {
		        	if(array_get($message,'total_fee')!=$order->total_price) {
		        		Log::info('微信回调订单金额'.array_get($message,'total_fee').'与系统中的订单实际支付金额.'.$order->total_price.'数据不一致');
		        		return false;
		        	}
		            $order->paid_at = array_get($message,'time_end'); // 更新支付时间为当前时间

				    $order->status = '2';
				    if($order->product_type==2) {
					    $order->status = 4;
					}         
		           

					$order->transaction_id = array_get($message,'transaction_id');

		            

		        // 用户支付失败
		        } elseif (array_get($message, 'result_code') === 'FAIL') {
		            $order->status = '0';
		        }
		} else {
			  	return $fail('通信失败，请稍后再通知我');
		}

		$order->save(); // 保存订单  

		// 减掉库存
		$op = OrderProduct::where(['order_id'=>$order->id])->first();
		$s['product_id'] = $op->product_id;
		$s['spec_id']    = $op->spec_id;
		$s['num']        = $op->product_num;
		ProductRepo::decreaseStore($s);




		// 推送小程序模板消息给用户
		$msg    = $order->toArray();
		$msg['product_info'] = OrderRepo::productInfo($order->id);
		$msg['openid']       = object_get($order,'user.small_openid');
		$msg['tel']          = object_get($order,'shop.phone');
		WechatTpl::sendTplMsg('paid',$msg); 



		// 推送公众号模板消息给管理员
		$shopUsers = ShopUser::where(['shop_id'=>$order->shop_id])->get();
		foreach ($shopUsers as $k => $su) {
			if(empty($su->wx_openid)) continue;			
			$msg['openid'] = $su->wx_openid;
			$msg['url']    = config('app.url').'/shop/order';
			WechatTpl::sendAccountMsgTpl('shop_order_new',$msg);
		}
		

		return true; // 返回处理完成
	});

		$response->send(); // return $response;
    }

    /**
     * 团购回调
     */
    public function groupPayNotify()
    {
    	$config = config('wechat.payment.default');    	
    	$app = Factory::payment($config);
    	
    	$response = $app->handlePaidNotify(function($message, $fail){
		    // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
    		Log::info('进入回调：'.json_encode($message));
		    $order = OrderRepo::find(['code'=>$message['out_trade_no']]);

		    if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
		        return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
		    }

		   

	if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
		        // 用户是否支付成功
		        if (array_get($message, 'result_code') === 'SUCCESS') {
		        	if(array_get($message,'total_fee')!=$order->total_price) {
		        		Log::info('微信回调订单金额'.array_get($message,'total_fee').'与系统中的订单实际支付金额.'.$order->total_price.'数据不一致');
		        		return false;
		        	}
		            $order->paid_at = array_get($message,'time_end'); // 更新支付时间为当前时间

		           
		            $order->status = '2';
		           

			$order->transaction_id = array_get($message,'transaction_id');

		            

		        // 用户支付失败
		        } elseif (array_get($message, 'result_code') === 'FAIL') {
		            $order->status = '0';
		        }
		} else {
			  	return $fail('通信失败，请稍后再通知我');
		}

		$order->status = 50; 
		$ogData['status'] = 50;
		$op = OrderProduct::where(['order_id'=>$order->id])->first();	// 获取product_id 检查下需要几个人 才能成团
		$product = Product::find($op->product_id);

		

		// 查查现在有多少参团
		$ogWhere['group_code'] = $order->group_code;
		$ogWhere['status']     = 50;
		$group_num = OrderGroup::where($ogWhere)->count();
		// 去 ordergroup表查查有没有信息，有就是跟团，没有就是新开团
		$og = OrderGroup::where($ogWhere)
						->orderBy('created_at','asc')
						->first();
		// 如果正好是最后一个那么直接满团
		if(array_get($product,'group_num')-$group_num==1) {
			// 如果是消费券状态改为4 直接发货
			if($order->product_type==2) {
			    $order->status    = 60;
			    $ogData['status'] = 60;
			    $oData['status']  = 60;
			} else {
				$order->status    = 55;
				$ogData['status'] = 55;
				$oData['status']  = 55;
			}


			$ogData['completed_at'] = date('Y-m-d H:i:s');
			

			Order::where($ogWhere)->update($oData);	
			OrderGroup::where($ogWhere)->update($ogData);
		}
		if($og) {
			$ogData['parent_id'] = $og->id;
			$ogData['end_at']    = $og->end_at;
		} else {
			$ogData['end_at'] = Carbon::now()->addHours($product->group_time);
		}				
		// 保存拼团信息
		$ogData['order_id']   = $order->id;
		$ogData['group_code'] = $order->group_code;
		$ogData['user_id']    = $order->user_id;
		$ogData['product_id'] = $op->product_id;
		
		OrderGroup::create($ogData);

		$order->save(); // 保存订单 

		// 减掉库存		
		$s['product_id'] = $op->product_id;
		$s['spec_id']    = $op->spec_id;
		$s['num']        = $op->product_num;
		ProductRepo::decreaseStore($s);

		


		// 用户小程序openid
		$small_openid = object_get($order,'user.small_openid');
		// 推送小程序模板消息给用户
		$msg    = $order->toArray();
		$msg['product_info'] = OrderRepo::productInfo($order->id);
		$msg['openid']       = $small_openid;
		$msg['tel'] 		 = object_get($order,'shop.phone');
		WechatTpl::sendTplMsg('paid',$msg); 

		// 拼团成功 通知用户
		if($order->status==55 || $order->status==60) {	
			
			
			$msg['user_info']    = OrderGroupRepo::userInfo($order->group_code);
			$group_users = OrderGroupRepo::getListByGroupCode($order->group_code);
			foreach ($group_users as $k => $gu) {
				$msg['form_id'] = $gu->prepay_id;
				$msg['code']    = $gu->group_code;
				$msg['openid']  = $gu->small_openid;
				WechatTpl::sendTplMsg('grouped_ok',$msg);
			}
			

			// 推送公众号模板消息给管理员
			$shopUsers = ShopUser::where(['shop_id'=>$order->shop_id])->get();
			foreach ($shopUsers as $k => $su) {
				if(empty($su->wx_openid)) continue;			
				$msg['openid']   = $su->wx_openid;
				$msg['truename'] = $order->truename.' '.object_get($order,'user.mobile');
				$msg['total_amount_txt'] = $order->total_price_txt;
				$msg['url']    = config('app.url').'/shop/order';
				WechatTpl::sendAccountMsgTpl('shop_order_new',$msg);
			} 
		} 

		
		

		return true; // 返回处理完成
	});

		$response->send(); // return $response;
    }

    /**
     * 红包充值回调
     */
    public function rechargeNotify()
    {
    	$config = config('wechat.payment.shop');    	
    	$app = Factory::payment($config);
    	Log::info('进入回调：');
    	$response = $app->handlePaidNotify(function($message, $fail){
		    // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单

		    $order = ShopRechargeRepo::find(['code'=>$message['out_trade_no']]);

		    if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
		        return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
		    }

		   

		    if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
		        // 用户是否支付成功
		        if (array_get($message, 'result_code') === 'SUCCESS') {
		        	if(array_get($message,'total_fee')!=$order->money) {
		        		Log::info('微信回调订单金额'.array_get($message,'total_fee').'与系统中的订单金额.'.$order->money.'数据不一致');
		        		return false;
		        	}
		            $order->paid_at = array_get($message,'time_end'); // 更新支付时间为当前时间
		            $order->status = '2';

		            $order->transaction_id = array_get($message,'transaction_id');

		        // 用户支付失败
		        } elseif (array_get($message, 'result_code') === 'FAIL') {
		            $order->status = '0';
		        }
		    } else {
		        return $fail('通信失败，请稍后再通知我');
		    }

		    $order->save(); // 保存订单

		    // 充值成功 生成红包
		    $data['recharge_id'] = $order->id;
		    $data['shop_id']     = $order->shop_id;
		    $data['money']       = $order->money;		    
		    ShopRechargeRepo::createEnvelop($data);

		   
		    return true; // 返回处理完成
		});

		$response->send(); // return $response;
    }

}
